<?php
/**
 * 模块分组模型
 *
 * @Author: yuanji <fenglangyj@139.com>
 * @DateTime: 12-11-3 下午1:44
 * @Copyright (c) 2012 http://www.magentoui.com All rights reserved.
 * @version  $Id: sss.php,v 1.0 uw Exp $
 * @Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
 */
class GroupModel extends Model {
	protected $_validate = array(
		array('name','require','名称必须'),
		);

	protected $_auto =	array(
        array('status',1,self::MODEL_INSERT,'string'),
		array('create_time','time',self::MODEL_INSERT,'function'),
	);

    /**
     * 获取分组列表树
     */
    public  function getGroupNameList($selected,$is_option=false){
        $items = $this->where('status=1')->order('parent_id,sort')->getField('id,parent_id as pid,name,title');
        $tree = array(); //格式化好的树
        foreach ($items as $item)
            if (isset($items[$item['pid']]))
                $items[$item['pid']]['son'][] = &$items[$item['id']];
            else
                $tree[] = &$items[$item['id']];
        if($is_option)$tree=$option = $this->option($tree,$selected);
        return $tree;
    }
    private function option($options,$selected,$level=0){
        $select = '';
        foreach ($options AS $var){
            $select .= '<option value="' . $var['id'] . '" ';
            $select .= ($selected == $var['id']) ? "selected='ture'" : '';
            $select .= '>';
            if ($level > 0){
                $select .= str_repeat('&nbsp;', $level * 4);
            }
            $select .= htmlspecialchars(addslashes($var['title']), ENT_QUOTES) .'_'.$var['id']. '</option>';
            if(!empty($var['son'])){
                $select .= $this->option($var['son'],$selected,$level+1);
            }
        }
        return $select;

    }
}
